import { Injectable, HttpException, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '@src/entities/user.entity';

@Injectable()
export class UserService {
  constructor (
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>
  ) { }


  async userList(): Promise<any> {
    return await this.userRepository.find();
  }

  async userDetails(id: number): Promise<any> {
    const user = await this.userRepository.findOne({ id });
    return {
      code: 0,
      message: '成功',
      data: user,
    }
  }

  async createUser(data: any): Promise<any> {
    try {
      const user = this.userRepository.create(data);
      return await this.userRepository.save(user);
    } catch (e) {
      Logger.error(e);
      throw new HttpException('创建错误', 200);
    }
  }

  async modifyUser(id: number, data: any): Promise<any> {
    return await this.userRepository.update({ id }, data);
  }

  async deleteUser(id: number): Promise<any> {
    return await this.userRepository.delete({ id });
  }
}
